# Copyright (c) 2011 Juan Manuel Borges Caño

# os.path.basename(filename)

import bpy

def export_jmbcmesh(context, filepath, use_some_setting):

	stream = open(filepath, 'w')

	scene = bpy.context.scene
	world = scene.world
	mesh = bpy.context.active_object
	tags = []
	for object in bpy.context.selected_objects:
		if object.name[0:4] == "Tag.":
			tags.append(object)

	# Vertices

	stream.write('vertices %s\n' % len(mesh.data.vertices))
	for vertex in mesh.data.vertices:
		co = mesh.matrix_world * vertex.co
		no = mesh.matrix_world * vertex.normal
		stream.write('coord %s %s %s\n' % (co.x, co.y, co.z))
		stream.write('normal %s %s %s\n' % (no.x, no.y, no.z))

	# Materials

	faces = []
	for material in mesh.data.materials:
		faces.append(0)
	for material in mesh.data.materials:
		for face, uvface in enumerate(mesh.data.uv_textures.active.data):
			if mesh.data.materials[mesh.data.faces[face].material_index] == material:
				faces[mesh.data.faces[face].material_index] += 1
	start = 0
	i = 0
	stream.write('materials %s\n' % len(mesh.data.materials))
	for material in mesh.data.materials:
		stream.write('name %s\n' % material.name)
		stream.write('start %s\n' % start)
		stream.write('faces %s\n' % faces[i])
		start += faces[i]
		i += 1

	# Faces

	stream.write('faces %s\n' % len(mesh.data.faces))
	for material in mesh.data.materials:
		for face, uvface in enumerate(mesh.data.uv_textures.active.data):
			if mesh.data.materials[mesh.data.faces[face].material_index] == material:
				stream.write('vertices')
				for vertex in mesh.data.faces[face].vertices:
					stream.write(' %s' % vertex)
				stream.write('\n')
				stream.write('normal')
				for normal in mesh.data.faces[face].normal:
					stream.write(' %s' % normal)
				stream.write('\n')
				stream.write('texcoords')
				for vertex in range(len(mesh.data.faces[face].vertices)):
					stream.write(' %s %s' % (uvface.uv[vertex][0], uvface.uv[vertex][1]))
				stream.write('\n')

	# Tags

	stream.write('tags %s\n' % len(tags))
	for tag in tags:
		stream.write('name %s\n' % tag.name[4:])
		co = tag.matrix_world * tag.data.vertices[0].co
		matrix = tag.matrix_world
		stream.write('matrix %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s\n' % (matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3], matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3], matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], co[0], co[1], co[2], matrix[3][3]))  

	stream.close()

	return {'FINISHED'}


from bpy_extras.io_utils import ExportHelper
from bpy.props import StringProperty


class ExportJMBCMesh(bpy.types.Operator, ExportHelper):
	'''Export to juanmabc Mesh format.'''

	bl_idname = "export.mesh"
	bl_label = "Export Mesh"
	filename_ext = ".mesh"
	filter_glob = StringProperty(default="*.mesh", options={'HIDDEN'})

	@classmethod
	def poll(cls, context):
		return context.active_object != None

	def execute(self, context):
		return export_jmbcmesh(context, self.filepath, None)


def menu_func_export(self, context):
	self.layout.operator(ExportJMBCMesh.bl_idname, text="Export to juanmabc Mesh")


def register():
	bpy.utils.register_class(ExportJMBCMesh)
	bpy.types.INFO_MT_file_export.append(menu_func_export)


def unregister():
	bpy.utils.unregister_class(ExportJMBCMesh)
	bpy.types.INFO_MT_file_export.remove(menu_func_export)


if __name__ == "__main__":
	register()
	bpy.ops.export.mesh('INVOKE_DEFAULT')
